import json
from datetime import datetime

from sanic.server import HttpProtocol
from sanic.response import json as _json, HTTPResponse


class DateTimeEncoder(json.JSONEncoder):
    def default(self, obj):
        if isinstance(obj, datetime):
            return obj.strftime("%Y-%m-%d %H:%M:%S")

        return json.JSONEncoder.default(self, obj)


class CustomHttpProtocol(HttpProtocol):
    def write_response(self, response):

        if isinstance(response, HTTPResponse):
            if 400 <= response.status < 500:
                response = {"msg": "request error"}
            elif response.status >= 500:
                response = {"msg": "server error"}
            else:
                response = response

        if isinstance(response, dict):
            response = _json(response, cls=DateTimeEncoder)

        return super().write_response(response)
